#include <iostream>
#include <vector>
#include <memory>
#include <algorithm>


//抽象观察者
class Observer
{
public:
    virtual void update(int date) = 0;
    virtual ~Observer() = default;
};
//抽象被观察者
class Subject
{
public:
    virtual void attach(std::shared_ptr<Observer> obser) = 0;
    virtual void detach(std::shared_ptr<Observer> obser) = 0;
    virtual void notify() = 0;
    virtual ~Subject() = default;
};
//具体观察者
class ConcreteObserver : public Observer
{
public:
    ConcreteObserver(std::string name):name(name)
    {

    }
    void update(int state)
    {
        //状态改变
        std::cout << name << "  state : " << state << std::endl;
    }
private:
    std::string name;
};
//具体被观察者
class ConcreteSubject : public Subject
{
public:
    //添加具体观察者
    void attach(std::shared_ptr<Observer> obser)
    {
        vecObserver.push_back(obser);
    }
    //删除具体观察者
    void detach(std::shared_ptr<Observer> obser)
    {
        vecObserver.erase(std::remove(vecObserver.begin(),vecObserver.end(),obser),vecObserver.end());
    }
    //通知观察者状态变化
    void notify()
    {
        for(const auto& obser : vecObserver)
        {
            obser.get()->update(state);
        }
    }
    void setState(int newState) {
        state = newState;
        notify();
    }
private:
    int state;
    std::vector<std::shared_ptr<Observer>> vecObserver;
};

int main()
{
    ConcreteSubject subject;
    
    auto AObserver = std::make_shared<ConcreteObserver>("A");
    auto BObserver = std::make_shared<ConcreteObserver>("B");
    subject.attach(AObserver);
    subject.attach(BObserver);

    subject.setState(10);
    subject.setState(20);

    subject.detach(AObserver);

    subject.setState(30);

}